var isEmpty = function (val) {
  // null or undefined
  if (val == null) return true;
  if (typeof val === "boolean") return false;
  if (typeof val === "number") return !val;
  if (val instanceof Error) return val.message === "";
  switch (Object.prototype.toString.call(val)) {
    // String or Array
    case "[object String]":
    case "[object Array]":
      return !val.length;
    // Map or Set or File
    case "[object File]":
    case "[object Map]":
    case "[object Set]": {
      return !val.size;
    }
    // Plain Object
    case "[object Object]": {
      return !Object.keys(val).length;
    }
  }
  return false;
};
function buildUrl(url, params) {
  let queryString = "";
  for (let key in params) {
    if (params.hasOwnProperty(key) && !isEmpty(params[key])) {
      queryString +=
        encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
    }
  }
  queryString = queryString.slice(0, -1);
  return url + "?" + queryString;
}
var getHashSearchParam = (key) => {
  var search = /(?<=#.*\?).*/.exec(window.location.href)?.[0];
  var usp = new URLSearchParams(search);
  return usp.get(key);
};
var getSearchParam = (key) => {
  var string = new URLSearchParams(window.location.search).get(key);
  if (!!string) {
    return string;
  }
  return getHashSearchParam(key);
};
function getRandomValue(array) {
  var randomIndex = Math.floor(Math.random() * array.length);
  return array[randomIndex];
}
function removeAllChildren(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}
let nanoid = (e = 21) => {
  let a = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  let t = "",
    r = crypto.getRandomValues(new Uint8Array(e));
  for (let n = 0; n < e; n++) t += a[63 & r[n]];
  return t;
};

function isContains(str, arr) {
  return arr.some((element) => str.includes(element));
}

function isDate(object) {
  return Object.prototype.toString.call(object) === "[object Date]";
}

function isString(object) {
  return Object.prototype.toString.call(object) === "[object String]";
}

function isNumber(object) {
  return Object.prototype.toString.call(object) === "[object Number]";
}

function isNumberString(object) {
  return !isNaN(parseFloat(object)) && isFinite(object);
}

function flatten(array) {
  let result = [];
  array.forEach((item) => {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result.push(item);
    }
  });
  return result;
}
function formatTime(timestamp) {
  if (isEmpty(timestamp)) return "";
  var language = (getSearchParam("language") ?? "en").toLocaleLowerCase();
  var unit = window.unit;
  if (
    isContains(
      timestamp,
      flatten(Object.values(unit).map((item) => Object.values(item)))
    )
  ) {
    return timestamp;
  }
  timestamp = new Date(timestamp).getTime();
  var now = Math.floor(Date.now());
  var diff = (now - timestamp) / 1000;
  var object = unit?.[language] ?? unit?.["default"];
  if (0 < diff && diff < 60) {
    return object?.now;
  } else if (0 < diff && diff < 60 * 60) {
    var num = Math.floor(diff / 60);
    var unit = num > 1 ? object?.minutes : object?.minute;
    if (unit.includes("占位")) {
      return unit.replace("占位", num);
    }
    return `${num}${unit}`;
  } else if (0 < diff && diff < 24 * 60 * 60) {
    var num = Math.floor(diff / 3600);
    var unit = num > 1 ? object?.hours : object?.hour;
    if (unit.includes("占位")) {
      return unit.replace("占位", num);
    }
    return `${num}${unit}`;
  } else if (0 < diff && diff < 7 * 24 * 60 * 60) {
    var num = Math.floor(diff / (24 * 60 * 60));
    var unit = num > 1 ? object?.days : object?.day;
    if (unit.includes("占位")) {
      return unit.replace("占位", num);
    }
    return `${num}${unit}`;
  } else {
    var date = new Date(timestamp);
    var year = date.getFullYear();
    var month = String(date.getMonth() + 1).padStart(2, "0");
    var day = String(date.getDate()).padStart(2, "0");
    var hours = String(date.getHours()).padStart(2, "0");
    var minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
}
function isNaturalNumbers(num) {
  return typeof num === "number" && num >= 0 && Math.floor(num) === num;
}

// async 函数返回一个 Promise 对象，可以使用 then 方法添加回调函数。
// await 是在等待一个Promise的异步返回
// 得到图片原始的宽高
// async function getImageSize(img) {
//   if (img.naturalWidth) {
//     // 适用于Firefox/IE9/Safari/Chrome/Opera浏览器
//     return {
//       width: img.naturalWidth,
//       height: img.naturalHeight,
//       ratio: img.naturalWidth / img.naturalHeight,
//     };
//   } else {
//     return await getImageSizeByUrl(img.src);
//   }
// }
// 使用Image对象获取图片真实宽高
// function getImageSizeByUrl(url) {
//   return new Promise(function (resolve, reject) {
//     let image = new Image();
//     image.onload = function () {
//       resolve({
//         width: image.naturalWidth,
//         height: image.naturalHeight,
//         ratio: image.naturalWidth / image.naturalHeight,
//       });
//     };
//     image.onerror = function () {
//       reject(new Error("error"));
//     };
//     image.src = url;
//   });
// }

function fullOpen(n, m) {
  var result = Math.random() * (m - n) + n;
  while (result == n) {
    result = Math.random() * (m - n) + n;
  }
  return Math.round(result);
}

function loadScript01(url, callback) {
  try {
    var script = document.createElement("script");
    script.async = true;
    script.setAttribute("crossorigin", "anonymous");
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback && callback();
        }
      };
    } else {
      script.onload = function () {
        callback && callback();
      };
    }
    script.src = url;
    document.head.appendChild(script);
  } catch (e) {
    console.error("Error loading script:", e);
  }
}

function loadScript02(url, callback) {
  try {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback && callback();
        }
      };
    } else {
      script.onload = function () {
        callback && callback();
      };
    }
    script.src = url;
    document.head.appendChild(script);
  } catch (e) {
    console.error("Error loading script:", e);
  }
}

// function loadScript03(id) {
//   var parser = new DOMParser();
//   var frament =
//     window.location.hostname === "hi-feeds.obnews.co"
//       ? `<script>
//   window.googletag = window.googletag || {cmd: []};
//   googletag.cmd.push(function() {
//     googletag.defineSlot('/23045591466/hi-list-E/hi_feeds_20241106_300x250_1', [300, 250], '${id}').addService(googletag.pubads());
//     googletag.pubads().collapseEmptyDivs();
//     googletag.enableServices();
//   });
// </script>`
//       : ["id-feeds.mobicrazy.com", "en-in-feeds.obnews.co"].includes(
//           window.location.hostname
//         )
//       ? `<script>(function(w,q){w[q]=w[q]||[];w[q].push(["_mgc.load"])})(window,"_mgq"); console.log('广告代码执行了')</script>`
//       : "";
//   var doc = parser.parseFromString(frament, "text/html");
//   var script = doc.querySelector("script");
//   document.head.appendChild(script);
// }
